<?php
namespace Model;
use DB;

class Msg extends \Model {
	public static function add($msg) {
		$data = $msg;
		$query = DB::select()->from('msgs');
		$query->where('sina_id', '=', $data['sina_id']);      
		$r = $query->execute();
		if (count($r->as_array()) > 0) return true;
		DB::insert('msgs')->set($data)->execute();
	}

	public static function get($idstr = array(), $per_page = 20, $offset = 0) {
		$query = DB::select()->from('msgs');
		$query->where('idstr', 'in', $idstr);
		$query->limit($per_page);
		$query->offset($offset);
		$query->order_by('created_at', 'desc');
		$r = $query->execute();
		return $r->as_array();
	}

	public static function get_cnt($idstr = array()) {
		$query = DB::select()->from('msgs');
		$query->where('idstr', 'in', $idstr);
		$r = $query->execute();
		return count($r->as_array());
	}

	public static function get_by_sina_id($sina_id) {
		$query = DB::select()->from('msgs');
		$query->where('sina_id', 'like', '%' . $sina_id . "%");
		$query->limit(1);
		$query->order_by('created_at', 'desc');
		$r = $query->execute();
		$r = $r->as_array();
		if (count($r) > 0) return $r[0]; 
		$query = DB::select()->from('msgs');
		$query->where('re_sina_id', 'like', '%' . $sina_id . "%");
		$query->limit(1);
		$query->order_by('created_at', 'desc');
		$r = $query->execute();
		$r = $r->as_array();
		if (count($r) > 0) {
			$v['idstr'] = $r[0]['re_idstr'];
			$v['sina_id'] = $r[0]['re_sina_id'];
			$v['screen_name'] = $r[0]['re_screen_name'];
			$v['original_pic'] = $r[0]['re_original_pic'];
			$v['text'] = $r[0]['re_text'];
			return $v;
		} 
		return array();
	}
}
